package com.hd.util.qrcode;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; 
/**
*@author hzhh123
*@time 2018年3月16日下午1:55:32 
*生成二维码
**/
@SuppressWarnings("unchecked")
public class QrcodeUtil {
	/** 
     * 生成二维码 
     *  
     * @param qrCodeData 
     *            二维码字符串 
     * @param filePath 
     *            文件路径 
     * @param charset 
     *            字符编码 
     * @param hintMap 
     * @param qrCodeheight 
     *            二维码的高度 
     * @param qrCodewidth 
     *            二维码的宽度 
     * @throws WriterException 
     * @throws IOException 
     */  
    public static void createQRCode(String qrCodeData, String filePath,  
            String charset, Map hintMap, int qrCodeheight, int qrCodewidth)  
            throws WriterException, IOException {  
        BitMatrix matrix = new MultiFormatWriter().encode(  
                new String(qrCodeData.getBytes(charset), charset),  
                BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight, hintMap);  
        MatrixToImageWriter.writeToFile(matrix, filePath.substring(filePath  
                .lastIndexOf('.') + 1), new File(filePath));  
    }  
  
    public static void createQrcodeInstance2(String qrCodeData, String filePath) {
    	try {
			encoderQRCode(qrCodeData,filePath);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    public static void createQrcodeInstance(String qrCodeData, String filePath) {
    	String charset = "UTF-8"; // "ISO-8859-1"  
    	Map hintMap = new HashMap();  
    	hintMap.put(EncodeHintType.MAX_SIZE, ErrorCorrectionLevel.M);  
    	try {
    		createQRCode(qrCodeData,filePath,charset,hintMap,280,280);
    		System.out.println("二维码生成成功！");
    	} catch (WriterException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	} catch (IOException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}
    }
    /** 
     * 读取二维码 
     *  
     * @param filePath 
     *            文件路径 
     * @param charset 
     *            字符编码 
     * @param hintMap 
     * @return 
     * @throws FileNotFoundException 
     * @throws IOException 
     * @throws NotFoundException 
     */  
    public static String readQRCode(String filePath, String charset, Map hintMap)  
            throws FileNotFoundException, IOException, NotFoundException {  
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(  
                new BufferedImageLuminanceSource(  
                        ImageIO.read(new FileInputStream(filePath)))));  
        Result qrCodeResult = new MultiFormatReader().decode(binaryBitmap,  
                hintMap);  
        return qrCodeResult.getText();  
    }  
    
    
    
    /** 
     * 生成二维码(QRCode)图片 
     * @param content 存储内容 
     * @param imgPath 图片路径 
     * @throws Exception  
     */  
      
    public static void encoderQRCode(String content, String imgPath) throws Exception {  
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();  
        Map hints = new HashMap();  
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");  
        hints.put(EncodeHintType.MARGIN, 0);  
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);  
        int width = 280;  
        int height = 280;  
        BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);  
        bitMatrix = updateBit(bitMatrix, 2);  
        MatrixToImageWriter.writeToFile(bitMatrix, "PNG", new File(imgPath));  
    }  
      
    /** 
     * 去掉空白的边框 
     * @param matrix 
     * @param margin 
     * @return 
     */  
    private static BitMatrix updateBit(BitMatrix matrix, int margin) {  
        int tempM = margin * 2;  
        int[] rec = matrix.getEnclosingRectangle(); // 获取二维码图案的属性  
        int resWidth = rec[2] + tempM;  
        int resHeight = rec[3] + tempM;  
        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight); // 按照自定义边框生成新的BitMatrix  
        resMatrix.clear();  
        for (int i = margin; i < resWidth; i++) { // 循环，将二维码图案绘制到新的bitMatrix中  
            for (int j = margin; j < resHeight; j++) {  
                if (matrix.get(i - margin + rec[0], j - margin + rec[1])) {  
                    resMatrix.set(i, j);  
                }  
            }  
        }  
        return resMatrix;  
    }  
    
    public static void main(String[] args) throws WriterException, IOException,  
    NotFoundException {  
		// 二维码字符串  
		String qrCodeData = "https://www.baidu.com/";  
		// 二维码名称  
		String filePath = "D:\\QRCode.png";  
		// 字符编码  
//		String charset = "UTF-8"; // "ISO-8859-1"  
//		Map hintMap = new HashMap();  
//		hintMap.put(EncodeHintType.MIN_SIZE, ErrorCorrectionLevel.M);  
//		createQRCode(qrCodeData, filePath, charset, hintMap, 50,  
//		        50);  
//		System.out.println("二维码图像创建成功!");  
//		
//		System.out.println("读取二维码数据: "  
//		        + readQRCode(filePath, charset, hintMap));  
		createQrcodeInstance(qrCodeData,filePath);
		}  
		
}  